package design.simdi.code.final_paper.site.panels.proiecte.idei;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.form.palette.Palette;
import org.apache.wicket.extensions.wizard.WizardModel;
import org.apache.wicket.extensions.wizard.WizardStep;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.model.util.CollectionModel;
import org.apache.wicket.model.util.ListModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import design.simdi.code.final_paper.core.entities.Bibliography;
import design.simdi.code.final_paper.core.entities.Idea;
import design.simdi.code.final_paper.core.entities.Keyword;
import design.simdi.code.final_paper.core.entities.Person;
import design.simdi.code.final_paper.core.entities.User;
import design.simdi.code.final_paper.core.services.ApplicationService;
import design.simdi.code.final_paper.core.services.ServiceException;
import design.simdi.code.final_paper.core.services.UserService;
import design.simdi.code.final_paper.site.application.MyAuthenticatedWebSession;
import design.simdi.code.final_paper.site.application.WicketApplication;
import design.simdi.code.final_paper.site.panels.MyWizard;
import design.simdi.code.final_paper.site.panels.MyWizardButtonBar;

/**
 * 
 * @author Marius Dumitriu - (Jun 21, 2010 - 4:12:59 PM)
 * 
 */
public class AddIdeaWizardPanel extends MyWizard {

	private static final long serialVersionUID = 1L;

	private Idea idea;

	private TextField<String> name;
	private TextArea<String> description;
	private String title;
	private String subtitle;
	private Palette<Keyword> paletteKeywords;
	private Palette<Bibliography> paletteBibliographies;
	@SpringBean
	private ApplicationService applicationService;

	@SpringBean
	private UserService userService;

	public AddIdeaWizardPanel(String id, Idea keyword) {
		super(id, false);

		if (keyword == null) {
			keyword = new Idea();
			title = "form.add.title";
			subtitle = "form.add.subtitle";
		} else {
			title = "form.modify.title";
			subtitle = "form.modify.subtitle";
		}
		this.idea = keyword;

		setDefaultModel(new CompoundPropertyModel<AddIdeaWizardPanel>(this));
		WizardModel model = new WizardModel();
		model.add(new IdeaNameStep());
		model.add(new IdeaKeywordsStep());
		model.add(new IdeaBibligraphiesStep());

		init(model);
		((WicketApplication) getApplication()).setShowErrors(false);
	}

	protected Component newButtonBar(String id) {
		return new MyWizardButtonBar(id, this, getForm()) {

			private static final long serialVersionUID = 1L;

			public void onFinishClick(AjaxRequestTarget target) {
				try {
					onFinish(target);
					IdeiTabPanel panel = new IdeiTabPanel("panel");
					panel.setOutputMarkupId(true);

					Page page = this.getPage();

					page.get("content:tabs:panel").replaceWith(panel);

					target.addComponent(page.get("content"));

				} catch (ServiceException e) {

					error(e.getMessage());
				}

			}

			public void onCancelClick(AjaxRequestTarget target) {
				onCancel(target);
				IdeiTabPanel panel = new IdeiTabPanel("panel");
				panel.setOutputMarkupId(true);

				Page page = this.getPage();

				page.get("content:tabs:panel").replaceWith(panel);

				target.addComponent(page.get("content"));
			}

		};
	}

	@SuppressWarnings("unchecked")
	public void onFinish(AjaxRequestTarget target) throws ServiceException {

		if (idea.getPerson() == null) {
			User currentUser = ((MyAuthenticatedWebSession) getSession()).getCurrentUser();

			Person p = userService.findPersonByUser(currentUser);

			idea.setPerson(p);
		}

		// cuvinte cheie
		Set<Keyword> keywordsSelectate = new HashSet<Keyword>((Collection<Keyword>) paletteKeywords
				.getDefaultModelObject());

		if (idea.getKeywords() == null)
			idea.setKeywords(new HashSet<Keyword>());

		for (Keyword key : keywordsSelectate)
			idea.getKeywords().add(key.clone());

		// bibliografii
		Set<Bibliography> bibliografiiSelectate = new HashSet<Bibliography>(
				(Collection<Bibliography>) paletteBibliographies.getDefaultModelObject());

		if (idea.getBibliographies() == null)
			idea.setBibliographies(new HashSet<Bibliography>());

		for (Bibliography b : bibliografiiSelectate)
			idea.getBibliographies().add(b.clone());

		applicationService.saveIdea(idea);
		onFinishMessage(target);
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setApplicationService(ApplicationService applicationService) {
		this.applicationService = applicationService;
	}

	public ApplicationService getApplicationService() {
		return applicationService;
	}

	private final class IdeaNameStep extends WizardStep {

		private static final long serialVersionUID = 1L;

		public IdeaNameStep() {
			super(new ResourceModel(title), new ResourceModel(subtitle));

			add(name = new TextField<String>("name", new PropertyModel<String>(idea, "name")));
			add(description = new TextArea<String>("description", new PropertyModel<String>(idea, "description")));
			name.setRequired(true);
			description.setRequired(false);
			name.setType(String.class);
			description.setType(String.class);

		}

	}

	private final class IdeaKeywordsStep extends WizardStep {

		private static final long serialVersionUID = 1L;

		@SuppressWarnings("unchecked")
		public IdeaKeywordsStep() {
			setTitleModel(new ResourceModel("ideakeywords.title"));
			setSummaryModel(new StringResourceModel("ideakeywords.summary", this, new Model<Idea>(idea)));

			List<Keyword> disponibile = applicationService.findAllKeywordsByPerson(getCurrentPerson());
			List<Keyword> selectate;
			if (idea.getKeywords() != null)
				selectate = new ArrayList<Keyword>(idea.getKeywords());
			else
				selectate = new ArrayList<Keyword>();

			disponibile.addAll(selectate);

			Collections.sort(disponibile, new Comparator() {

				public int compare(Object arg0, Object arg1) {
					Keyword s1 = (Keyword) arg0;
					Keyword s2 = (Keyword) arg1;
					return s1.getName().compareToIgnoreCase(s2.getName());
				}
			});

			IChoiceRenderer<Keyword> renderer = new ChoiceRenderer<Keyword>("name", "name");

			paletteKeywords = new Palette<Keyword>("palette", new ListModel<Keyword>(selectate),
					new CollectionModel<Keyword>(disponibile), renderer, 10, false) {

				private static final long serialVersionUID = 1L;

				protected Component newAvailableHeader(String componentId) {
					return new Label(componentId, new ResourceModel("available"));
				}

				protected Component newSelectedHeader(String componentId) {
					return new Label(componentId, new ResourceModel("selected"));
				}

			};

			Form<?> form = new Form("form");

			add(form);
			form.add(paletteKeywords);

		}
	}

	private final class IdeaBibligraphiesStep extends WizardStep {

		private static final long serialVersionUID = 1L;

		@SuppressWarnings("unchecked")
		public IdeaBibligraphiesStep() {
			setTitleModel(new ResourceModel("ideabibliographies.title"));
			setSummaryModel(new StringResourceModel("ideabibliographies.summary", this, new Model<Idea>(idea)));

			List<Bibliography> disponibile = applicationService.findAllBibliographiesByPerson(getCurrentPerson());
			List<Bibliography> selectate;
			if (idea.getBibliographies() != null)
				selectate = new ArrayList<Bibliography>(idea.getBibliographies());
			else
				selectate = new ArrayList<Bibliography>();

			disponibile.addAll(selectate);

			Collections.sort(disponibile, new Comparator() {

				public int compare(Object arg0, Object arg1) {
					Bibliography s1 = (Bibliography) arg0;
					Bibliography s2 = (Bibliography) arg1;
					return s1.getName().compareToIgnoreCase(s2.getName());
				}
			});

			IChoiceRenderer<Bibliography> renderer = new ChoiceRenderer<Bibliography>("name", "name");

			paletteBibliographies = new Palette<Bibliography>("palette", new ListModel<Bibliography>(selectate),
					new CollectionModel<Bibliography>(disponibile), renderer, 10, false) {

				private static final long serialVersionUID = 1L;

				protected Component newAvailableHeader(String componentId) {
					return new Label(componentId, new ResourceModel("available"));
				}

				protected Component newSelectedHeader(String componentId) {
					return new Label(componentId, new ResourceModel("selected"));
				}

			};

			Form<?> form = new Form("form");

			add(form);
			form.add(paletteBibliographies);

		}
	}

	public Person getCurrentPerson() {
		User currentUser = ((MyAuthenticatedWebSession) getSession()).getCurrentUser();

		Person p = userService.findPersonByUser(currentUser);
		return p;
	}
}
